from redis_connection import redis_conn as redis
import requests
import logging
import config
import json

logger = logging.getLogger()


def send_to_user(open_id, message):
    try:
        requests.post("https://api.weixin.qq.com/cgi-bin/message/custom/send",
                      params={"access_token": redis.hget(config.PUB_ACCESS_TOKEN, "token").decode()},
                      data=json.dumps({
                          "touser": open_id,
                          "msgtype": "text",
                          "text": {
                              "content": message
                          }
                      }, ensure_ascii=False).encode("utf-8"),
                      headers={"Content-Type": "application/json; charset=utf-8"})
        logger.info(f"[SEND_TO_USER] 向{open_id}发送消息:{message}成功。")
    except requests.ConnectionError:
        logger.error(f"[SEND_TO_USER] 向{open_id}发送消息:{message}失败。")


def send_template_message(open_id, template_id, message, jump_to=""):
    try:
        msg_body = dict()
        msg_body["touser"] = open_id
        msg_body["template_id"] = template_id
        if len(jump_to) > 0:
            msg_body["url"] = jump_to
        msg_body["data"] = message
        response = requests.post("https://api.weixin.qq.com/cgi-bin/message/template/send",
                                 params={"access_token": redis.hget(config.PUB_ACCESS_TOKEN, "token").decode()},
                                 data=json.dumps(msg_body,
                                                 ensure_ascii=False).encode("utf-8"),
                                 headers={"Content-Type": "application/json; charset=utf-8"})
        msg_resp = response.json()
        if "errcode" in msg_resp:
            if msg_resp["errcode"] == 0:
                logger.info(f"[SEND_TEMPLATE_MSG] 向{open_id}发送模板消息请求成功。")
            else:
                logger.error(f"[SEND_TEMPLATE_MSG] 向{open_id}发送模板消息请求失败，错误码：{msg_resp['errcode']}")
    except requests.ConnectionError:
        logger.error(f"[SEND_TEMPLATE_MSG] 向{open_id}发送模板消息失败。")
